/**
 * Created by Taller on 17/3/1.
 */
var express = require('express'),
    io = require('socket.io');

var app = express();
app.use(express.static(__dirname));
var server = app.listen(8888);

var ws = io.listen(server);

ws.on('connection', function(client){
    //客户端连接注册
    client.on('join', function(userId){
        // 检查是否有重复
        if(!checkUserId(userId)){
            client.userId = userId;     //加入到在线客户端列表中
            console.log('join','客户端->'+client.userId+'连接成功');
        }
    });
    // 监听发送消息
    client.on('send.message', function(msg){
        client.broadcast.emit('send.message',client.userId,msg);
    });
    // 断开连接时
    client.on('disconnect', function(){
        if(client.userId){
            //client.broadcast.emit('send.message','系统',  client.userId + '断开了连接!');
            console.log('disconnect:',client.userId + '断开了连接!')
        }
    })
});

var checkUserId = function(_userId){
    for(var k in ws.sockets.sockets){
        if(ws.sockets.sockets.hasOwnProperty(k)){
            if(ws.sockets.sockets[k] && ws.sockets.sockets[k].userId == _userId){
                return true;
            }
        }
    }
    return false;
}

